import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class TextReverseBackend {
    public static void main(String[] args) throws IOException {
        // 创建HTTP服务器，监听8080端口
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);

        // 处理API请求
        server.createContext("/api/process", new HttpHandler() {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                try {
                    // 设置CORS头
                    exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
                    exchange.getResponseHeaders().add("Access-Control-Allow-Methods", "POST, OPTIONS");
                    exchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type");

                    // 处理OPTIONS预检请求
                    if ("OPTIONS".equalsIgnoreCase(exchange.getRequestMethod())) {
                        exchange.sendResponseHeaders(204, -1);
                        return;
                    }

                    // 只接受POST请求
                    if (!"POST".equalsIgnoreCase(exchange.getRequestMethod())) {
                        exchange.sendResponseHeaders(405, -1); // 方法不允许
                        return;
                    }

                    // 读取请求体
                    String requestBody;
                    try (Scanner scanner = new Scanner(exchange.getRequestBody(), StandardCharsets.UTF_8.name())) {
                        requestBody = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
                    }

                    // 解析输入文本
                    String inputText = "";
                    String[] params = requestBody.split("&");
                    for (String param : params) {
                        String[] keyValue = param.split("=");
                        if (keyValue.length > 1 && "input".equals(keyValue[0])) {
                            inputText = URLDecoder.decode(keyValue[1], StandardCharsets.UTF_8);
                            break;
                        }
                    }

                    // 处理文本（反转字符串）
                    String reversedText = new StringBuilder(inputText).reverse().toString();

                    // 准备JSON响应
                    String jsonResponse = String.format("{\"output\": \"%s\"}", reversedText.replace("\"", "\\\""));

                    // 发送响应
                    exchange.getResponseHeaders().set("Content-Type", "application/json; charset=UTF-8");
                    byte[] responseBytes = jsonResponse.getBytes(StandardCharsets.UTF_8);
                    exchange.sendResponseHeaders(200, responseBytes.length);
                    try (OutputStream os = exchange.getResponseBody()) {
                        os.write(responseBytes);
                    }
                } catch (Exception e) {
                    // 错误处理
                    String errorResponse = "{\"error\": \"处理请求时发生错误\"}";
                    exchange.getResponseHeaders().set("Content-Type", "application/json");
                    byte[] errorBytes = errorResponse.getBytes(StandardCharsets.UTF_8);
                    exchange.sendResponseHeaders(500, errorBytes.length);
                    try (OutputStream os = exchange.getResponseBody()) {
                        os.write(errorBytes);
                    }
                }
            }
        });

        // 启动服务器
        server.start();
        System.out.println("Server started on port 8080");
    }
}